<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    // 1. 函数的参数表（arguments）是一个类数组对象，补全下面的函数，将 arguments 转为真正的数组并返回

    // function arg2Array(arg) {
    // 	//...
    // 	return arg;
    // }

    function arg2Array() {
      let arg = Array.from(arguments);
      return arg
    }
    // arg2Array(1, 3, 5, 7, 9, 'sgfs');

    // 简单实现一个数组的深拷贝(无需考虑 Date 对象，Symbol 等情况)
    function deepCloneArray(array) {
      // 1. for循环实现
      // let res = []
      // for (let i = 0; i < array.length; i++) {
      //   res.push(array[i])
      // }
      // return res

      // 2. slice方法
      // let res = array.slice(0);
      // return res

      // 3. concat方法
      // let res = array.concat()
      // return res

      // 4. ES6拓展运算符方法
      return [...array]
    }

    // let arr1 = [1, 2, 3, 5];
    // let arr2 = deepCloneArray(arr1);
    // arr2[1] = 4;
    // console.log(arr1);
    // console.log(arr2);

    // 3. 数组去重并排序,去除如下数组的重复元素，并从小到大排序
    let arr = [1, 1, 1, 4, 68, , 6, 6, 9, 8, 7, 3, 5, 24, 5, 6, 89, 45, 12, 23, 56];
    // let arr = [1, 1, 1, 4, 68, , 6];

    function noRepeatAndSort(arr) {
      let deleRepeatEle = arr.filter(function (value, index, self) {
        return self.indexOf(value) === index;
      })
      return deleRepeatEle.sort((a, b) => {
        return a - b;
      })
    }

    // console.log(noRepeatAndSort(arr));

    var people = [
      { name: 'Alice', age: 21 },
      { name: 'Max', age: 20 },
      { name: 'Jane', age: 20 }
    ];
    // 将people转化为如下格式：
    // {
    //   20: [
    //     { name: 'Max', age: 20 },
    //     { name: 'Jane', age: 20 }
    //   ],
    //     21: [{ name: 'Alice', age: 21 }]
    // }
    // let group = {
    //   20: [
    //     { name: 'Max', age: 20 },
    //     { name: 'Jane', age: 20 }
    //   ],
    //   21: [{ name: 'Alice', age: 21 }]
    // }

    // console.log(group);

    var objTest = [
      { province: '湖南', city: '长沙', age: 18 },
      { province: '湖南', city: '株洲', age: 18 },
      { province: '广东', city: '深圳', age: 19 },
      { province: '广东', city: '广州', age: 20 },
      { province: '北京', city: '西城区', age: 21 },
    ]

    function groupBy(objectArray, property) {
      return objectArray.reduce(function (acc, obj) {
        var key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }

    // console.log(groupBy(objTest, 'age'))
    // console.log(groupBy(people, 'age'))

    // function groupBy(arr, property) {

    // }


    // const groupBy = () => {
    //   return arr.reduce((pre, current, index) => {
    //     pre[current.province] = pre[current.province] || [];
    //     pre[current.province].push({ city: current.city, age: current.age });
    //     return pre;
    //   }, {});
    // }

    // console.log(groupBy())


    // function arrayGroupBy(list, groupId) {
    //   function groupBy(array, f) {
    //     const groups = {}
    //     array.forEach(function (o) {
    //       console.log('o', o);
    //       const group = JSON.stringify(f(o))
    //       groups[group] = groups[group] || []
    //       groups[group].push(o)
    //     })

    //     return groups;
    //     // return Object.keys(groups).map(function (group) {
    //     //     return groups[group]
    //     // })
    //   };
    //   return groupBy(list, function (item) {
    //     return item[groupId]
    //   });
    // };

    var response = [
      { name: '张三', age: 14 },
      { name: '李四', age: 15 },
      { name: '王五', age: 16 },
      { name: '小明', age: 15 },
      { name: '小云', age: 16 }
    ];

    // var responseObj = arrayGroupBy(response, 'age');

    // console.log('分组前：', response);
    // console.log('分组后：', responseObj);


    // 字符串 替换 模板
    let testPeople = {
      name: 'test',
      age: 22,
      gender: '男'
    }
    //我们平常用字符串写的就是这样了吧
    // let html = template('demotem', user)
    let str = '你好，{{name}}，系统显示您的年龄是{{age}}，性别为{{gender}}'

    //下面是封装的代码
    function template(tpl, obj) {

      let reg = /{{(\w*)}}/
      let arr = []

      console.log(reg.exec(tpl));
      console.log(obj['' + reg.exec(tpl)[1]]);
      while (arr = reg.exec(tpl)) {
        tpl = tpl.replace(arr[0], obj[arr[1]])
      }

      return tpl
    }
    // template(str, testPeople)

    let str1 = "hello world";
    function reverseStr(str) {
      return str.split('').reverse().join('');
    }
    reverseStr(str1)
    // console.log(reverseStr(str1));


    // 数组扁平化
    let arrFlat = [1, [1, [2, [3, 1, 4], 5], 5, 5], 8, 9, 6, 3];
    function flatArray(array) {
      // return arrFlat.flat();
      // return array.toString().split(',').map((item) => {
      //   return +item
      // })
      // array.some( item => {
      //   console.log(item);
      // });
      while (array.some(item => Array.isArray(item))) {
        // console.log('执行');
        array = [].concat(...array)
        // console.log(array);
      }

      return array
    }
    // console.log(flatArray(arrFlat));

    // Array => Tree
    let arrTarget = [
      { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null },
      { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null },
      { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null },
      { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null },
      { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null },
      { "id": "15", "parentId": "11", "text": "Lucy", "level": "3", "children": null }
    ]

    let result = [
      {
        "id": "12", "parentId": "0", "text": "Man", "level": "1", "children":
          [
            { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null },
            { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }
          ]
      },
      {
        "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children":
          [
            {
              "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children":
                [
                  { "id": "15", "parentId": "11", "text": "Girl0", "level": "3", "children": null }
                ]
            }
          ]
      }
    ]


    function array2Tree(arr) {
      // 空数组
      let result = [];
      // 判断不是数组  直接返回
      if (!Array.isArray(arr)) {
        console.log('错误！请检查传入的参数格式!');
        return result
      }
      // 遍历  删除  children 属性  做初始化操作
      arr.forEach(item => {
        delete item.children;
      });
      //  空对象

      let map = {};
      arr.forEach(item => {
        map[item.id] = item;
      });

      /**
       * map对象的 键: 是每个id  值：对应的item
       * 1: {id: 1, pid: 0, name: "body"}
       * 2: {id: 2, pid: 1, name: "title"}
       * 3: {id: 3, pid: 2, name: "div"}
       */

      arr.forEach((item, i) => {

        // item.pid 为0时 返回underfined
        let parent = map[item.parentId];

        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          // 这里push的item是pid为0的数据
          result.push(item);
        }
      });
      console.log(result);
      return result;
    }
    array2Tree(arrTarget)
    // console.log(array2Tree(arrTarget));


    // function array2Tree(arr) {
    //   let result = [];
    //   let map = {};
    //   arr.forEach(item => {
    //     map[item.id] = item;
    //   });
    //   arr.forEach(item => {
    //     let parent = map[item.parentId];
    //     if (parent) {
    //       (parent.children || (parent.children = [])).push(item);
    //     } else {
    //       result.push(item);
    //     }
    //   });
    //   return result;
    // }
    // array2Tree(arrTarget)

  </script>
</body>

</html>